package com.msb.mall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.msb.common.utils.HttpUtil;
import com.msb.common.utils.PageUtils;
import com.msb.common.utils.Query;
import com.msb.mall.member.dao.MemberDao;
import com.msb.mall.member.entity.MemberEntity;
import com.msb.mall.member.entity.MemberLevelEntity;
import com.msb.mall.member.entity.vo.MemberLoginVo;
import com.msb.mall.member.entity.vo.MemberRegisterVo;
import com.msb.mall.member.entity.vo.SocialUser;
import com.msb.mall.member.exception.PhoneExistException;
import com.msb.mall.member.exception.UserNameExistException;
import com.msb.mall.member.service.MemberLevelService;
import com.msb.mall.member.service.MemberService;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelService memberLevelService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 完成会员的注册功能
     * @param vo
     */
    @Override
    public void register(MemberRegisterVo vo) {
        MemberEntity entity = new MemberEntity();
        //设置会员等级
        MemberLevelEntity defaultStatus = memberLevelService.getOne(new QueryWrapper<MemberLevelEntity>().eq("default_status", 1));
        entity.setLevelId(defaultStatus.getId());
        entity.setGrowth(defaultStatus.getCommentGrowthPoint());
        //添加对应的手机号是不能重复的
        boolean mobile = this.baseMapper.exists(new QueryWrapper<MemberEntity>().eq("mobile", vo.getPhone()));
        if(mobile){
           throw new PhoneExistException();
        }
        boolean username = this.baseMapper.exists(new QueryWrapper<MemberEntity>().eq("username", vo.getUserName()));
        if(username){
            throw new UserNameExistException();
        }

        entity.setUsername(vo.getUserName());
        entity.setNickname(vo.getUserName());

        //需要加密，不能明文
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        entity.setPassword(encoder.encode(vo.getPassword()));
        entity.setMobile(vo.getPhone());
        //设置其他默认值
        entity.setCreateTime(new Date());
        entity.setStatus(1);
        this.save(entity);
    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {
        //1、根据账号或者手机号查询用户信息
        MemberEntity entity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>()
                .eq("username", vo.getUserName())
                .or()
                .eq("mobile", vo.getUserName())
        );
        if(entity != null){
            //2、账号或手机号存在，根据密码加密后的校验来判断成功
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            boolean matches = encoder.matches(vo.getPassword(), entity.getPassword());
            if(matches){
                //登录成功
                return entity;
            }
        }
        return null;
    }

    @Override
    public MemberEntity oauth2Login(SocialUser user) {
        //如果该用户是第一次社交登录，需要注册
        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>()
                .eq("social_uid", user.getUid()));
        if(memberEntity != null){
            //说明当前已经注册过了
            MemberEntity entity = new MemberEntity();
            entity.setId(memberEntity.getId());
            entity.setAccessToken(user.getAccessToken());
            entity.setExpiresIn(user.getExpiresIn());
            this.baseMapper.updateById(entity);
            memberEntity.setExpiresIn(user.getExpiresIn());
            memberEntity.setAccessToken(user.getAccessToken());
            return memberEntity;
        }
        //如果不是第一次，需要登录
        MemberEntity entity = new MemberEntity();
        entity.setSocialUid(user.getUid());
        entity.setAccessToken(user.getAccessToken());
        entity.setExpiresIn(user.getExpiresIn());
        //通过token 调用微博接口获取用户信息
        try {
            Map<String,String>  querys = new HashMap<>();
            querys.put("access_token", user.getAccessToken());
            querys.put("uid", user.getUid());
            HttpResponse get = HttpUtil.doPost("https://api.weibo.com/",
                    "2/users/show.json",
                    "get",
                    new HashMap<>(),
                    null,
                    querys);
            if(get.getStatusLine().getStatusCode() == 200){
                String string = EntityUtils.toString(get.getEntity());
                JSONObject jsonObject = JSON.parseObject(string);
                String screenName = jsonObject.getString("screen_name");
                String gender = jsonObject.getString("gender");
                String profileImageUrl = jsonObject.getString("profile_image_url");
                entity.setUsername(screenName);
                entity.setNickname(screenName);
                entity.setGender(Objects.equals(gender, "m") ? 1 : 0);
                entity.setHeader(profileImageUrl);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        //注册用户信息
        this.save(entity);
        return entity;
    }

}
